package com.example.weather.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by hanjun on 2016/7/31.
 */
public class DataHelper extends SQLiteOpenHelper {

    private final static String TAG = "DatabaseHelper";
    private static final int mDataBaseVersion = 1;// 数据库版本号
    private static final String mDataBaseName = "Weather.db";// 数据库名
    private static DataHelper mDatabaseHelper;
    public static final String mPlanTable = "PersonInfoTable";//个人信息表

    private DataHelper(Context context)
    {
        super(context, mDataBaseName, null, mDataBaseVersion);
        // 数据库实际被创建是在getWritableDatabase()或getReadableDatabase()方法调用时
        Log.d("DatabaseHelper", "DatabaseHelper Constructor");
        // CursorFactory设置为null,使用系统默认的工厂类
    }

    public static DataHelper getInstance(Context context){
        if(mDatabaseHelper == null){
            mDatabaseHelper = new DataHelper(context);
        }
        return mDatabaseHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // 调用时间：数据库第一次创建时onCreate()方法会被调用
        // onCreate方法有一个 SQLiteDatabase对象作为参数，根据需要对这个对象填充表和初始化数据
        // 这个方法中主要完成创建数据库后对数据库的操作
        Log.d("DatabaseHelper", "DatabaseHelper onCreate");
        createPersonInfoTable(db);

    }

    private void createPersonInfoTable(SQLiteDatabase db){
        StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("CREATE TABLE " + mPlanTable + " (");
        sBuffer.append("_id INTEGER NOT NULL PRIMARY KEY, ");
        sBuffer.append("year INTEGER,");
        sBuffer.append("month INTEGER,");
        sBuffer.append("date INTEGER,");
        sBuffer.append("content INTEGER,");
        sBuffer.append("startTime TEXT,");
        sBuffer.append("endTime TEXT);");
        db.execSQL(sBuffer.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // 调用时间：如果DATABASE_VERSION值被改为别的数,系统发现现有数据库版本不同,即会调用onUpgrade
        // onUpgrade方法的三个参数，一个 SQLiteDatabase对象，一个旧的版本号和一个新的版本号
        // 这样就可以把一个数据库从旧的模型转变到新的模型
        // 这个方法中主要完成更改数据库版本的操作
        Log.d("DatabaseHelper", "DatabaseHelper onUpgrade");
        db.execSQL("DROP TABLE IF EXISTS " + mPlanTable);
        onCreate(db);
        // 上述做法简单来说就是，通过检查常量值来决定如何，升级时删除旧表，然后调用onCreate来创建新表
        // 一般在实际项目中是不能这么做的，正确的做法是在更新数据表结构时，还要考虑用户存放于数据库中的数据不丢失
    }

    public Map<String,Object> getPlan(int year , int month,int date){
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.query(mPlanTable, null, "year = ? and month = ? and date = ?", new String[]{year+"",month+"",date+""}, null, null, null);
        Map<String,Object> map = new HashMap<>();
        int indexDate = cursor.getColumnIndex("date");
        int indexContent = cursor.getColumnIndex("content");
        int indexStartTime = cursor.getColumnIndex("startTime");
        int indexEndTime = cursor.getColumnIndex("endTime");
        if(cursor.moveToFirst()) {
            map.put("content", cursor.getString(indexContent));
            map.put("startTime", cursor.getString(indexStartTime));
            map.put("endTime", cursor.getString(indexEndTime));
        }
        return map;
    }

    public Set<Integer> getHavePlanDate(int year , int month){
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.query(mPlanTable, null, "year = ? and month = ?", new String[]{year+"",month+""}, null, null, null);
        Set<Integer> set = new HashSet<>();
        int indexDate = cursor.getColumnIndex("date");
        for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            set.add(cursor.getInt(indexDate));
        }
        return set;
    }

    public void insertAndUpdatePlan(int year,int month,int date ,String content,String startTime,String endTime){
        SQLiteDatabase db = getReadableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("content", content);
        cv.put("startTime", startTime);
        cv.put("endTime", endTime);
        int line = db.update(mPlanTable, cv, "year =? and month = ? and date = ?", new String[]{year + "",month +"", date+""});
        if (line == 0) {
            cv.put("year", year);
            cv.put("month", month);
            cv.put("date", date);
            long insertNum = db.insert(mPlanTable, "year", cv);
            Log.d(TAG, "insertFriendTable : insert " + insertNum + " records");
        }
    }

    public boolean deletePlan(int year,int month,int date){
        SQLiteDatabase db = getReadableDatabase();
        int line = db.delete(mPlanTable, "year = ? and month = ? and date = ?",new String[]{year+"",month +"",date+""});
        return true;
    }
}
